Python Code Samples
π Python Basic Examplesβ
Read, understand, and practice these Python examples to better understand the Python language. These simple Python programs will help us understand Pythonβs basic programming concepts.
All the programs on this page are tested and should work on all platforms.
1. π’ Python Program to Print Hello Worldβ
A very simple Python program that displays βHello, World!β on the screen.
print("Hello, World!")
2. π Python Program to Get the Dictionary Intersectionβ
Python examples to find common items between 2 or more dictionaries i.e. dictionary intersection items.
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 2, 'c': 4, 'd': 5}
intersection = dict1.items() & dict2.items()
print("Common items:", intersection)
More ways to achieve the same.
3. π Python Program to Find the Largest or Smallest N Itemsβ
Python examples to find the largest (or the smallest) N elements from a collection of elements using nlargest()
and nsmallest()
functions from heapq
library.
import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
largest_three = heapq.nlargest(3, nums)
smallest_three = heapq.nsmallest(3, nums)
print("3 Largest:", largest_three)
print("3 Smallest:", smallest_three)
More ways to achieve the same.
4. π¦ Python Program to Unpack Tuples into Variables or Argumentsβ
Python examples to unpack an N-element tuple or sequence into a collection of N variables.
# Unpacking into variables
data = ('ACME', 50, 91.1)
name, shares, price = data
print("Name:", name)
print("Shares:", shares)
print("Price:", price)
# Unpacking into function arguments
def sample_func(x, y, z):
print(x + y + z)
params = (10, 20, 30)
sample_func(*params)
More ways to achieve the same.
5. π Python Program to Use max()
and min()
Functionsβ
Python examples to find the largest (or the smallest) item in a collection (e.g. list, set or array) of comparable elements using max()
and min()
methods.
values = [10, 4, 23, 1, 56, 3]
max_val = max(values)
min_val = min(values)
print("Maximum value:", max_val)
print("Minimum value:", min_val)
π§ Happy Learning !!